<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tbody v-if="arr.length">
          <tr v-for="(item, index) in arr" :key="item.id">
            <td>{{ index + 1 }}</td>
            <td>{{ item.uname }}</td>
            <td>{{ item.age }}</td>
            <td>{{ item.gender }}</td>
            <td>
              <button @click="deleteId(item.id)">删除</button>
              <button @click="edit(item.id)">编辑</button>
            </td>
          </tr>
        </tbody>
        <tbody v-else>
          <tr>
            <td colspan="5">
              <span class="none">暂无数据</span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      flag: '',
      uname: '',
      age: '',
      gender: '',
      arr: [],
    }
  },
  methods: {
    add() {
      if (this.uname && this.age && this.gender) {
        const obj = {
          id: this.uname + this.age + this.gender,
          uname: this.uname,
          age: this.age,
          gender: this.gender,
        }
        if (this.flag !== '') {
          this.arr.splice(
            this.arr.findIndex((item) => {
              return item.id === this.flag
            }),
            0,
            obj
          )
        } else {
          this.arr = [...this.arr, obj]
        }
        this.uname = ''
        this.age = ''
        this.gender = ''
        this.arr = this.arr.filter((item) => item.id !== this.flag)
        this.flag = ''
      } else {
        alert('输入框不能为空！')
      }
    },
    deleteId(id) {
      this.arr = this.arr.filter((item) => item.id !== id)
    },
    edit(id) {
      const newArr = this.arr.filter((item) => item.id === id)
      this.uname = newArr[0].uname
      this.age = newArr[0].age
      this.gender = newArr[0].gender
      this.flag = id
    },
  },
}
</script>
